package cn.labbook.bluetooth.controller;

import cn.labbook.bluetooth.common.ResultDto;
import cn.labbook.bluetooth.constant.WxRetryConstant;
import cn.labbook.bluetooth.entity.WxRetry;
import cn.labbook.bluetooth.entity.wxpay.WXPay;
import cn.labbook.bluetooth.service.IWxRetryService;
import cn.labbook.bluetooth.util.weixin.pay.PayUtil;
import cn.labbook.bluetooth.util.weixin.pay.UUIDHexGenerator;
import cn.labbook.bluetooth.util.weixin.pay.XmlUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import lombok.extern.slf4j.Slf4j;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Slf4j
@Controller
@RequestMapping({"/wxretry"})
public class WxRetryController extends AbstractController {

    @Autowired
    private IWxRetryService wxRetryService;

    private final String mch_id = "1491927112";

    private final String appid = "wxafeeae8c758d838d";


    @RequestMapping({"test"})
    @ResponseBody
    public ResultDto test(Integer status) {
        System.out.println("输入的status："+ status);
        System.out.println("对比结果：" + status.equals(WxRetryConstant.STATUS.REFUSE));
        System.out.println("对比结果：" + status.equals(WxRetryConstant.STATUS.REVIEWED));
        System.out.println("对比结果：" + status.equals(WxRetryConstant.STATUS.PASS));
        return success();
    }

    @RequestMapping({"page"})
    @ResponseBody
    public ResultDto page(Page<WxRetry> page, Integer status) {
        LambdaQueryWrapper<WxRetry> lambda = (new QueryWrapper()).lambda();
        if (status.intValue() != -1)
            lambda.eq(WxRetry::getExamineStatus, status);
        IPage<WxRetry> result = this.wxRetryService.page(page, lambda);
        return (result.getTotal() > 0L) ? success(page) : fail("暂无数据");
    }

    @RequestMapping({"examine"})
    @ResponseBody
    public ResultDto examine(Integer id, Integer status) throws DocumentException {
        WxRetry wxRetry = new WxRetry();
        wxRetry.setId(id);
        WxRetry wr = this.wxRetryService.getById(wxRetry);
        System.out.println("------------重试记录" + wr);
        System.out.println("------------审核状态" + wr.getExamineStatus());
        System.out.println("------------请求审核状态" + status);

        if (wr != null) {
            if (wr.getExamineStatus().equals(WxRetryConstant.STATUS.REFUSE) || wr.getExamineStatus().equals(WxRetryConstant.STATUS.PASS))
                return fail("改记录已审核过,请勿重复审核");
            if (status.equals(WxRetryConstant.STATUS.REFUSE)) {
                wxRetry.setExamineStatus(2);
                this.wxRetryService.updateById(wxRetry);
                return success("审核成功");
            }
            if (status.equals(WxRetryConstant.STATUS.PASS)) {
                WXPay wxPay = new WXPay();
                wxPay.setAmount(wxRetry.getAmount());
                wxPay.setMch_appid(appid);
                wxPay.setMchid(mch_id);
                wxPay.setDesc("佐客房客电费充值");
                wxPay.setNonce_str(UUIDHexGenerator.generate());
                wxPay.setOpenid(wxRetry.getOpenid());
                wxPay.setPartner_trade_no(wxRetry.getOutTradeNo());
                wxPay.setCheck_name("NO_CHECK");
                wxPay.setSpbill_create_ip("127.0.0.1");
                Map<String, Object> sParaTemp = new HashMap<>();
                sParaTemp.put("mch_appid", wxPay.getMch_appid());
                sParaTemp.put("mchid", wxPay.getMchid());
                sParaTemp.put("nonce_str", wxPay.getNonce_str());
                sParaTemp.put("partner_trade_no", wxPay.getPartner_trade_no());
                sParaTemp.put("amount", wxPay.getAmount());
                sParaTemp.put("spbill_create_ip", wxPay.getSpbill_create_ip());
                sParaTemp.put("check_name", wxPay.getCheck_name());
                sParaTemp.put("desc", wxPay.getDesc());
                sParaTemp.put("openid", wxPay.getOpenid());
                Map sPara = PayUtil.paraFilter(sParaTemp);
                String prestr = PayUtil.createLinkString(sPara);
                String mysign = PayUtil.sign(prestr, "&key=zk123sqweqdsadZK9120392018490184", "utf-8").toUpperCase();
                wxPay.setSign(mysign);
                String respXml = XmlUtil.messagePayToXML(wxPay);
                respXml = respXml.replace("__", "_");
                String param = respXml;
                String result = PayUtil.ssl("https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers", param);
                Map<Object, Object> map = new HashMap<>();
                InputStream in = new ByteArrayInputStream(result.getBytes());
                SAXReader reader = new SAXReader();
                Document document = reader.read(in);
                Element root = document.getRootElement();
                List<Element> elementList = root.elements();
                for (Element element : elementList)
                    map.put(element.getName(), element.getText());
                String return_code = map.get("return_code").toString();
                String return_msg = map.get("return_msg").toString();
                String result_code = map.get("result_code").toString();
                if ("SUCCESS".equals(return_code) && "SUCCESS".equals(result_code)) {
                    wxRetry.setExamineStatus(1);
                    wxRetry.setRemark(return_msg);
                    this.wxRetryService.updateById(wxRetry);
                    return success(return_msg);
                }
                wxRetry.setExamineStatus(0);
                wxRetry.setRemark(return_msg);
                this.wxRetryService.updateById(wxRetry);
                return fail(return_msg);
            }
            return fail("参数错误");
        }
        return fail("未找到该记录");
    }
}
